import {
	t,
	tm,
	i18n
} from '@/locale/index'

let _debounceTimeout = null,
	_throttleRunning = false

/**
 * 防抖
 * @param {Function} 执行函数
 * @param {Number} delay 延时ms
 */
export const debounce = (fn, delay = 500) => {
	clearTimeout(_debounceTimeout);
	_debounceTimeout = setTimeout(() => {
		fn();
	}, delay);
}

/**
 * 节流
 * @param {Function} 执行函数
 * @param {Number} delay 延时ms
 */
export const throttle = (fn, delay = 500) => {
	if (_throttleRunning) {
		return;
	}
	_throttleRunning = true;
	fn();
	setTimeout(() => {
		_throttleRunning = false;
	}, delay);
}
/**
 * toast
 */
export const msg = (params, callback) => {
	setTimeout(() => {
		uni.showToast({
			title: typeof params === 'string' ? params : params.title,
			duration: params.item || 1500,
			mask: params.mask || true,
			icon: params.icon || 'none'
		})

		setTimeout(() => {
			if (typeof callback === "function") {
				callback()
			};
		}, params.item || 1500)
	}, 0)
}
/**
 * 检查登录
 * @return {Boolean}
 */
export const isLogin = (options = {}) => {
	return uni.getStorageSync('account') ? true : false;
}
/**
 * 获取页面栈
 * @param {Number} preIndex为1时获取上一页
 * @return {Object}
 */
export const prePage = (preIndex = 1) => {
	const pages = getCurrentPages();
	const prePage = pages[pages.length - (preIndex + 1)];

	return prePage
}

//二维数组去重
export const getUnique = array => {
	let obj = {}
	return array.filter((item, index) => {
		let newItem = item + JSON.stringify(item)
		return obj.hasOwnProperty(newItem) ? false : obj[newItem] = true
	})
}

//获取小程序code
export const getMpCode = (provider) => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider,
			success: res => {
				resolve(res.code);
			}
		})
	})
}

// isTabbarPage
export const isTabbarPage = () => {
	const pages = getCurrentPages();
	const currentPage = pages[pages.length - 1];
	const tabBarList = ['pages/index/index', 'pages/category/category', 'pages/find/find', 'pages/cart/cart',
		'pages/account/home/home'
	];
	return tabBarList.indexOf(currentPage.route) !== -1;
}

// 生成随机字符串
export const randomString = (length) => {
	let str = '';
	const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	for (let i = 0; i < length; i++) {
		str += chars.charAt(Math.floor(Math.random() * chars.length));
	}
	return str;
}

export const requestHeader = () => {
	let system = uni.getSystemInfoSync();

	return {
		'content-type': 'application/json',
		'accept': 'application/json',
		'Authorization': 'Bearer ' + uni.getStorageSync('access-token'),
		// #ifdef MP-WEIXIN
		'platform': 'miniapp',
		// #endif
		// #ifdef APP-PLUS
		'platform': 'app',
		'version': plus.runtime.version,
		'client': system.platform,
		// #endif
		'currency': uni.getStorageSync('user_currency') || uni.getStorageSync('settings')?.system?.currency ||
			'CNY',
		'locale': uni.getStorageSync('user_language') || 'zh_cn',
	}
}

// 后退
export const back = (delta = 1) => {
	uni.navigateBack({
		delta
	})
}

// 返回 页面栈 getCurrentPages() 中 指定 route 页面
export const backTo = (route) => {
	const pages = getCurrentPages();
	const index = pages.findIndex(e => e.route === route);
	const delta = pages.length - index - 1;
	back(delta)
}

// languages
export const languages = () => [{
		name: '简体中文',
		code: 'zh_cn'
	},
	{
		name: 'English',
		code: 'en'
	},
	{
		name: '繁体中文',
		code: 'zh_hk'
	},
]

// 设置页面 title
export const setPageTitle = () => {
	const pages = getCurrentPages();
	const currentPage = pages[pages.length - 1];
	const routeArr = currentPage.route.split('/');
	routeArr.shift();
	routeArr.pop();
	const route = routeArr.join('/').replace(/\//g, '.');

	uni.setNavigationBarTitle({
		title: t(route + '.heading_title')
	})
}

// 设置 tabBar 的多语言
export const setTabBarLanguage = () => {
	const tabBar = [...i18n.global.tm('tabBar')]
	tabBar.forEach((e, i) => uni.setTabBarItem({
		index: i,
		text: e
	}))
}

// 跳转页面
export const navigateTo = (url, params) => {
	let query = '';
	if (params) {
		query = Object.keys(params).map(key => key + '=' + params[key]).join('&');
	}

	// 要排除的页面
	const excludePages = ['/pages/account/register/register', '/pages/account/login/login',
		'/pages/account/forget/forget',
	]

	// 判断是 '/pages/account' 开头的页面，如果是，判断是否登录
	if (url.indexOf('/pages/account') === 0 && excludePages.indexOf(url) === -1) {
		if (!uni.getStorageSync("account")) {
			uni.navigateTo({
				url: '/pages/account/login/login'
			})

			return;
		}
	}

	uni.navigateTo({
		url: url + (query ? '?' + query : '')
	})
}

// 更新 tabbar 购物车角标数量
export const updateCartTabBar = () => {
	// if (uni.getStorageSync("cart_number")) {
	// 	uni.setTabBarBadge({
	// 		index: 2,
	// 		text: uni.getStorageSync("cart_number") + "" || "",
	// 	})
	// } else {
	// 	return uni.removeTabBarBadge({
	// 		index: 2
	// 	})
	// }
}

// 获取当前语言 code
export const getLanguageCode = () => {
	return uni.getStorageSync('user_language') || 'zh_cn';
}

// 根据 语言 code 判断国内还是国外，然后显示对应格式的地址
export const formatAddress = (address) => {
	const languageCode = getLanguageCode();
	if (languageCode === 'zh_cn') {
		return address.country + ' ' + address.zone + ' ' + address.city + ' ' + address.address_1 + ' ' + address
			.address_2 + ' ' + address.zipcode;
	} else {
		return address.address_1 + ' ' + address.address_2 + ' ' + address.city + ' ' + address.zone + ' ' + address
			.country + ' ' + address.zipcode;
	}
}

// 替换词条 "error_required": "请输入{name}", {name} 替换为对应的词条
export const replaceI18n = (key, ...args) => {
	const str = tm(key);
	return str.replace(/{([^}]+)}/g, function(match, key) {
		return args[0][key];
	});
}

export const linkTypeFormat = (link) => {
	let url = '';

	if (!link.value) {
		return;
	}

	switch (link.type) {
		case 'product':
			url = '/pages/product/product?id=' + link.value;
			break;
		case 'category':
			url = '/pages/category/list/list?id=' + link.value;
			break;
		case 'brand':
			url = '/pages/category/list/list?brand_id=' + link.value;
			break;
		case 'page':
			url = '/pages/webview/index?src=pages/' + link.value;
			break;
		default:
			url = '';
	}

	uni.navigateTo({
		url
	})
}

// 判断类型集合
export const checkStr = (str, type) => {
	switch (type) {
		case 'mobile': //手机号码
			return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
		case 'tel': //座机
			return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
		case 'card': //身份证
			return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
		case 'mobileCode': //6位数字验证码
			return /^[0-9]{6}$/.test(str)
		case 'pwd': //密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线
			return /^(?:\d|[a-zA-Z]){6,18}$/.test(str)
		case 'payPwd': //支付密码 6位纯数字
			return /^[0-9]{6}$/.test(str)
		case 'postal': //邮政编码
			return /[1-9]\d{5}(?!\d)/.test(str);
		case 'QQ': //QQ号
			return /^[1-9][0-9]{4,9}$/.test(str);
		case 'email': //邮箱
			return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
		case 'money': //金额(小数点2位)
			return /^\d*(?:\.\d{0,2})?$/.test(str);
		case 'URL': //网址
			return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
		case 'IP': //IP
			return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
		case 'date': //日期时间
			return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) ||
				/^(\d{4})\-(\d{2})\-(\d{2})$/
				.test(str)
		case 'number': //数字
			return /^[0-9]$/.test(str);
		case 'english': //英文
			return /^[a-zA-Z]+$/.test(str);
		case 'chinese': //中文
			return /^[\\u4E00-\\u9FA5]+$/.test(str);
		case 'lower': //小写
			return /^[a-z]+$/.test(str);
		case 'upper': //大写
			return /^[A-Z]+$/.test(str);
		case 'HTML': //HTML标记
			return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
		default:
			return true;
	}
}

// 获取币种类型
export const getCurrencyType = (id) => {
	let lang = uni.getStorageSync('user_language');
	let currencys = uni.getStorageSync('settings').currencies;
	let currency = currencys.find(item => item.id == id);
	let type = currency ? lang == 'en' ? currency.code : currency.name : "未知";
	return type;
}